#include "soundplayer.h"

QMap<QString, QSound*>* SoundPlayer::sounds = 0;

void SoundPlayer::playSound(QString name)
{
    if (sounds->contains(name.toLower()))
        sounds->value(name.toLower())->play();
}

void SoundPlayer::loopSound(QString name, int times)
{
    if (sounds->contains(name.toLower()))
    {
        sounds->value(name.toLower())->setLoops(times);
        sounds->value(name.toLower())->play();
    }
}

void SoundPlayer::stopSound(QString name)
{
    if (sounds->contains(name.toLower()))
        sounds->value(name.toLower())->stop();
}

void SoundPlayer::stopAllSounds()
{
    QStringList keys = QStringList(sounds->keys());
    QString key;

    foreach (key, keys)
    {
        sounds->value(key)->stop();
    }
}

bool SoundPlayer::isSoundPlaying(QString name)
{
    if (sounds->contains(name.toLower()))
        return !sounds->value(name.toLower())->isFinished();
    else
        return false;
}

void SoundPlayer::setResourceDirectory(QString path)
{
    QDir directory(path);

    if (directory.exists())
    {
        delete sounds;
        sounds = new QMap<QString, QSound*>();

        QStringList nameFilters;
        nameFilters.append("*.wav");
        directory.setNameFilters(nameFilters);

        directory.setFilter(QDir::Files | QDir::NoDotAndDotDot);

        QStringList files;
        files = directory.entryList();
        QString file;

        foreach (file, files)
        {
            QSound* sound = new QSound(directory.filePath(file), 0);
            file.remove(".wav", Qt::CaseInsensitive);
            file = file.toLower();
            sounds->insert(file, sound);
        }
    }
}
